<?php
class ModelDeviceToken extends Model {
	/*
	 * validateToken
	 * 验证动态令牌
	 * @param string $device_imei 设备imei
	 * @param string $token 动态令牌
	 * @return int 返回-1代表验证不通过，否则返回设备id
	 */
	public function validateToken($device_imei,$token){
		$sql = 'SELECT `device_id` FROM `token` WHERE token=:token AND `out_time`>NOW() AND device_id=(SELECT `device_id` FROM `device` WHERE `device_imei`=:device_imei AND `is_pass`=1)';
		$params = array(
			':device_imei'=>$this->db->escape($device_imei),
			':token'=>$this->db->escape($token)
		);
		$query = $this->db->query($sql,$params);
		if($query->num_rows>0){
			return (int)$query->row['device_id'];
		}else{
			return -1;
		}
	}
	
	public function updateToken($device_id,$token){
		$sql = 'REPLACE `token` SET `token`=:token,`generate_time`=NOW(),`device_id`=:device_id,`out_time`=:out_time';
		$params = array(
			':token'=>$this->db->escape($token),
			':device_id'=>(int)$device_id,
			':out_time'=>date('Y-m-d H:i:s',strtotime('+10 minute'))
		);
		
		$this->db->query($sql,$params);
		return $this->db->countAffected()>0;
	}
}
